//
//  HLJSWebViewController.m
//  JS2WebView
//
//  Created by hongliang on 16/3/7.
//  Copyright (c) 2016年 hongliang. All rights reserved.
//

#import "HLJSWebViewController.h"

@interface HLJSWebViewController ()
@property(nonatomic, strong)JSContext* jsContext;
@end

@implementation HLJSWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (JSContext*)jsContext {
    return [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (JSValue*)jsMethod:(NSString*)name arguments:(NSString*)arg1,... {
    if (![name isKindOfClass:[NSString class]] ||
        name.length <= 0) {
        return nil;
    }
    
    NSMutableString* jsString = [NSMutableString stringWithString:name];
    [jsString appendString:@"("];
    
    
    if ([arg1 isKindOfClass:[NSString class]] &&
        arg1.length > 0) {
        NSMutableArray* arrayStrings = [NSMutableArray array];
        [arrayStrings addObject:[NSString stringWithFormat:@"'%@'",arg1]];
        
        va_list paramList = NULL;
        va_start(paramList, arg1);
        NSString* paramItem = nil;
        while ((paramItem = va_arg(paramList, id))) {
            [arrayStrings addObject:[NSString stringWithFormat:@"'%@'",paramItem]];
        }
        va_end(paramList);
        if (arrayStrings.count > 0) {
            [jsString appendString:[arrayStrings componentsJoinedByString:@","]];
        }
    }
    
    [jsString appendString:@")"];
    
    return [self.jsContext evaluateScript:jsString];
}

- (void)registerOCMethod:(NSString*)name block:(JCCallbackBlock)callback {
    self.jsContext[name] = callback;
}

- (void)registerOCModel:(NSString*)name objc:(id)objc {
    self.jsContext[name] = objc;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
